package com.zpl.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zpl.order.entity.Address;
import com.zpl.order.mapper.AddressMapper;
import com.zpl.order.service.AddressService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {

    @Resource
    private AddressMapper addressMapper;

    @Resource
    private AddressService addressService;

    @Override
    public boolean insert(Address address) {
        if(address.getDefaultAddress()==1){
            if(addressService.selectByDefaultAddress(address.getMemberId())!=null){
                Address address1 = addressService.selectByDefaultAddress(address.getMemberId());
                address1.setDefaultAddress(0);
                addressService.update(address);
            }
        }
        if(addressMapper.insert(address)>0){
            return true;
        }
        return false;
    }

    @Override
    public boolean delete(Long id) {
        if (addressMapper.deleteById(id)>0){
            return true;
        }
        return false;
    }

    @Override
    public boolean update(Address address) {
        if(address.getDefaultAddress()==1){
            if(addressService.selectByDefaultAddress(address.getMemberId())!=null){
                Address address1 = addressService.selectByDefaultAddress(address.getMemberId());
                address1.setDefaultAddress(0);
                addressMapper.updateById(address1);
            }
        }
        if (addressMapper.updateById(address)>0){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public Address selectById(Long id) {
        return addressMapper.selectById(id);
    }

    @Override
    public List<Address> selectByMemberId(Long memberId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("member_id", memberId);
        List<Address> list = addressMapper.selectList(queryWrapper);
        return list;
    }

    @Override
    public Address selectByDefaultAddress(Long memberId){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("member_id", memberId);
        queryWrapper.eq("default_address", "1");
        Address address = addressMapper.selectOne(queryWrapper);
        return address;
    }
}
